package com.ash.threadpool;

import java.util.Observable;

public abstract class Task extends Observable implements Runnable {

    private String key;

    public Task(String key) {
        this.key = key;
    }

    @Override
    public void run() {
        try {
            execute();

        } finally {
            afterFinallyTask();
        }
    }

    public String getKey() {
        return key;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((key == null) ? 0 : key.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null) {
            return false;
        }

        if (getClass() != obj.getClass()) {
            return false;
        }

        Task other = (Task) obj;
        if (key == null) {
            if (other.key != null) {
                return false;
            }
        } else if (!key.equals(other.key)) {
            return false;
        }

        return true;
    }

    protected abstract void execute();

    private void afterFinallyTask() {
        setChanged();

        notifyObservers();
    }

    @Override
    public String toString() {
        return "Task [key=" + key + "]";
    }

}
